package com.bbs.toutiao.service.client.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.bbs.toutiao.aspect.SysLog;
import com.bbs.toutiao.entity.UserEntity;
import com.bbs.toutiao.exception.BaseException;
import com.bbs.toutiao.exception.ExceptionEnum;
import com.bbs.toutiao.mapper.admin.UserMapper;
import com.bbs.toutiao.mapper.clinet.ClientUserEditorMapper;
import com.bbs.toutiao.mapper.clinet.ClientUserMapper;
import com.bbs.toutiao.service.admin.impl.UserServiceImpl;
import com.bbs.toutiao.service.client.ClientUserService;
import com.bbs.toutiao.vo.client.UserPhonePasswordVo;
import com.bbs.toutiao.vo.client.UserVo;
import com.bbs.toutiao.vo.user.RegisterVo;
import com.bbs.toutiao.vo.user.UpdateStatusVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * 描述:
 * 作者： zhangBin
 * 时间： 2023/10/8 11:03
 * 版本： 1.0
 */

@Slf4j
@Service
public class ClientUserServiceImpl implements ClientUserService {

    @Resource
    ClientUserMapper clientUserMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    ClientUserEditorMapper userEditorMapper;


    /**
     *
     * @param lrVo
     * @param token
     * @return int
     */
    @SysLog("用户更新密码")
    @Transactional
    @Override
    public int updateUserPassword(UserPhonePasswordVo lrVo, String token) {
        String password = MD5.create().digestHex(lrVo.getPassword(), StandardCharsets.UTF_8);
        lrVo.setPassword(password);
        int userId;
        try {
            JWT jwt = JWTUtil.parseToken(token);
            userId = Integer.parseInt(jwt.getPayload("userId").toString());
        } catch (Exception e) {
            throw new BaseException(ExceptionEnum.TOKEN_FONT_ERROR);
        }
        lrVo.setId(userId);
        int i = clientUserMapper.updatePasswordByPhoneId(lrVo);
        if (i == 0) {
            throw new BaseException(ExceptionEnum.PASSWORD);
        }
        return  i;
    }

    /**
     * 修改用户手机号，需要查询是否被注册
     * @param lrVo
     * @param token
     * @return
     */
    @SysLog("用户修改手机号")
    @Override
    public int updateUserPhone(UserPhonePasswordVo lrVo, String token) {
        int userId;
        try {
            JWT jwt = JWTUtil.parseToken(token);
            userId = Integer.parseInt(jwt.getPayload("userId").toString());
        } catch (Exception e) {
            throw new BaseException(ExceptionEnum.TOKEN_FONT_ERROR);
        }
        String phone = clientUserMapper.getPhone(lrVo.getPhone());
        if (lrVo.getPhone().equals(phone)){
            throw new BaseException(ExceptionEnum.PHONE_MAN);
        }
        lrVo.setId(userId);
        return clientUserMapper.updatePhoneById(lrVo);
    }


    /**
     * 1:账号和密码登录<br/>
     * 2:手机号登录手机号未注册则自动注册
     * @param lrVo
     * @return {@link UserEntity}
     */
    @SysLog("用户登录")
    @Override
    public UserEntity login(UserPhonePasswordVo lrVo, String name) {
        if (name.equals("ACCOUNT")) {
            String password = MD5.create().digestHex(lrVo.getPassword(), StandardCharsets.UTF_8);
            lrVo.setPassword(password);
        }
//        log.info(lrVo+"");
        UserEntity user = clientUserMapper.selectUserByAccountAndPasswordOrPhone(lrVo);
        if (name.equals("PHONE")){
            if (user==null && !Objects.equals(lrVo.getPhone(), "")){
                RegisterVo registerVo = new RegisterVo();
                registerVo.setPhone(lrVo.getPhone());
                String account = String.valueOf(DateUtil.currentSeconds());
                registerVo.setUserName("用户"+ StrUtil.sub(account,-5,account.length()));
                registerVo.setPassword(StrUtil.sub(account,-5,account.length()));
                //如果注册成功为true
                boolean b = UserServiceImpl.register(registerVo,userMapper);
                if (b){
                    //如果注册成功则查询数据库
                    user = clientUserMapper.selectUserByAccountAndPasswordOrPhone(lrVo);
                    user.setPassword("");
                    return user;
                }
            }
        }
        if (user == null) {
            throw new BaseException(ExceptionEnum.USER_NOT_PASSWORD);
        }
        UpdateStatusVo statusVo = new UpdateStatusVo();
        int status = user.getStatus();
        long cur = DateUtil.currentSeconds();  //获取当前时间戳
        UserServiceImpl.userStatus(statusVo, cur, user, status, userMapper, log);
        user.setPassword("");
        return user;
    }

    /**
     * 描述：修改背景图片
     * @param token
     * @param image
     * @return
     */
    @SysLog("用户修改背景图片")
    @Override
    public int updateUserBackground(String token, String image) {
        int userId;
        try {
            JWT jwt = JWTUtil.parseToken(token);
            userId = Integer.parseInt(jwt.getPayload("userId").toString());
        } catch (Exception e) {
            throw new BaseException(ExceptionEnum.TOKEN_FONT_ERROR);
        }
        return userEditorMapper.updateUserBackground(userId,image);
    }

    @Override
    public UserVo selectUserInfo(Integer userId) {
        return userEditorMapper.getUserInfoByUserId(userId);
    }


}
